package com.lzy.business.controller.agent;

import com.github.pagehelper.PageInfo;
import com.lzy.business.facade.AgentCommissionBillFacade;
import com.lzy.business.request.AgentCommissionBillRequest;
import com.lzy.business.response.AgentBilltStatisticsInfoResponse;
import com.lzy.business.response.AgentCommissionBillResponse;
import com.lzy.framework.component.PageBean;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.excel.SimpleExcelExportUtils;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.CollectionUtils;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.WebUtils;
import com.lzy.product.dtos.agent.AgentBillScreenListDto;
import com.lzy.product.dtos.agent.AgentCommissionBillDto;
import com.lzy.web.exception.GenericException;
import com.lzy.web.response.excel.AgentCommissionBillExportResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin/agent/commissionBill")
public class AgentCommissionBillController {
    private static final Logger logger = LoggerFactory.getLogger(AgentCommissionBillController.class);

    @Autowired
    private AgentCommissionBillFacade agentCommissionBillFacade;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String commissionBillList() {
        return "/agent/statistical/commission_view";
    }

    /**
     * 分拥统计列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/agentCommissionBillList", method = RequestMethod.GET)
    @ResponseBody
    public PageBean agentProtocolList(AgentCommissionBillRequest request) {
        Ensure.that(request).isNotNull("04000001");
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        PageInfo<AgentCommissionBillDto> pageInfo = agentCommissionBillFacade.getAgentCommissionBillList(pager, DozerUtils.map(request, AgentCommissionBillDto.class));
        if (pageInfo != null) {
            return new PageBean<>(pageInfo.getTotal(), DozerUtils.maps(pageInfo.getList(), AgentCommissionBillResponse.class));
        }
        return null;
    }

    /**
     * 分拥统计
     *
     * @return
     */
    @RequestMapping(value = "/statistics", method = RequestMethod.GET)
    @ResponseBody
    public AgentBilltStatisticsInfoResponse statistics() {
        AgentBilltStatisticsInfoResponse agentBilltStatisticsInfoResponse = agentCommissionBillFacade.getStatistics();
        return agentBilltStatisticsInfoResponse;
    }

    /**
     * 可筛选项列表
     * @return
     */
    @RequestMapping(value = "/screenList", method = RequestMethod.GET)
    @ResponseBody
    public Result screenList(Integer type){
        List<AgentBillScreenListDto> agentBillScreenListDtoList = agentCommissionBillFacade.getAgentBillScreenList(type);
        Map<String,Object> map  = new HashMap<>();
        map.put("agentBillScreenListDtoList",agentBillScreenListDtoList);
        return new Result(map);
    }

    /**
     * 可筛选项体系列表
     * @return
     */
    @RequestMapping(value = "/systemList", method = RequestMethod.GET)
    @ResponseBody
    public Result systemList(Long sourceId,Integer type){
        List<AgentBillScreenListDto> agentBillScreenListDtoList = agentCommissionBillFacade.getSystemList(sourceId,type);
        Map<String,Object> map  = new HashMap<>();
        map.put("systemList",agentBillScreenListDtoList);
        return new Result(map);
    }

    /**
     * 导出订单
     *
     * @param request
     * @param response
     * @param agentCommissionBillRequest
     */
    @RequestMapping(value = "/exportAgentCommissionBill")
    public void exportOrderList(HttpServletRequest request, HttpServletResponse response, AgentCommissionBillRequest agentCommissionBillRequest) {
        try {
        Pager pager = new Pager();
        pager.setPageSize(10000);
        AgentCommissionBillDto dto = DozerUtils.map(agentCommissionBillRequest, AgentCommissionBillDto.class);
        PageInfo<AgentCommissionBillDto> pageInfo = agentCommissionBillFacade.getAgentCommissionBillList(pager, dto);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            List<AgentCommissionBillDto> list = pageInfo.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                if (list.size() > 10000)
                    throw new GenericException("导出数据量过大,请重新输入检索条件,分批导出！");
                LinkedList<AgentCommissionBillExportResponse> voList = new LinkedList<>();
                AgentCommissionBillExportResponse vo;
                for (AgentCommissionBillDto agentCommissionBillDto : list) {
                    vo = new AgentCommissionBillExportResponse();
                    BeanUtils.copyProperties(agentCommissionBillDto, vo);
                    voList.add(vo);
                }
                SimpleExcelExportUtils excelExportService = new SimpleExcelExportUtils();
                HSSFWorkbook wb = new HSSFWorkbook();
                if (voList != null && voList.size() > 0) {
                    wb = excelExportService.generateExcel(voList);
                }
                String fileName = "分佣统计表" + sdf.format(new Date()) + ".xls";
                // 设定输出文件头
                WebUtils.prepareDownloadFile(fileName, "application/msexcel", request, response);
                OutputStream out = response.getOutputStream();
                wb.write(out);
                out.close();
            } else {
                logger.error("没有可执行数据：分拥统计数据导出EXCEL失败！");
            }
        } catch (Exception e) {
            logger.error("分拥统计数据导出EXCEL失败！", e);
            throw new GenericException("分拥统计数据导出EXCEL失败");
        }
    }
}
